$(function () {
    $(window).resize(function() {
        updateTableSize();
    });
});

function updateTableSize(){
    var width = $('.layui-card').width() - 50;
    var height = $(document).height() - 160;
    // layui-card 宽度 - 50
    // 浏览器高度 - 160
    $('.layui-table-body').css({'width':width,'height':height});
    $('.layui-table-header').css({'width':width});
}

/**
 * Created by wxf on 2020/9/11.
 */
//初始化查询栏年份和弹窗内年份日期控件
layui.use('laydate', function () {
    var laydate = layui.laydate;
    //年选择器
    laydate.render({
        elem: '#beginMonth'
        , type: 'month'
        , min: "2020-09-01"
        , value: new Date()
        , btns: ['now', 'confirm']
    });
    laydate.render({
        elem: '#endMonth'
        , type: 'month'
        , min: "2020-09-01"
        , value: new Date()
        , btns: ['now', 'confirm']
    });
});
layui.use('form', function () {
    var form = layui.form;
    $.ajax({
        url: $ctx + '/company/companyList',
        dataType: 'json',
        type: 'get',
        async: false,
        success: function (data) {
            var res = data.data;
            $.each(res, function (index, item) {
                $('#companies').append(new Option(item.name, item.id));// 下拉菜单里添加元素
            });
            form.render("select");
            initEmpList();
        }
    });
    form.on('select(company)', function (data) {
        initEmpList();
    });
});
var empsMap = {}, allEmpNoArr = [], selEmpNoArr = [], empSelctDom;
function initEmpList() {
    $.ajax({
        url: $ctx + '/hrmResource/empList',
        dataType: 'json',
        type: 'get',
        data: {companyId: $('#companies').val()},
        async: false,
        success: function (data) {
            var res = data.data;
            $('#emps').html("");
            var emps = [];
            $.each(res, function (index, item) {
                emps.push({
                    name: item.name,
                    value: item.loginid
                });
                empsMap[item.loginid] = item;
                allEmpNoArr.push(item.loginid);
            });
            empSelctDom = xmSelect.render({
                el: '#emps',
                language: 'zn',
                filterable: true,
                toolbar: {
                    show: true,
                    list: ["ALL", "CLEAR"]
                },
                data: emps
            });
            //重新渲染 固定写法
            selEmpNoArr = allEmpNoArr;
        }
    });

}
var tableList = [];
var beginMonth = "", endMonth = "", empNo = "", companyId = "";
//项目列表
layui.use('table', function () {
    var $ = layui.$;
    var table = layui.table;
    beginMonth = $("#beginMonth").val();
    endMonth = $("#endMonth").val();
    companyId = $("#companies").val();
    // empNo = $("#emps").val();
    var tableRender = table.render({
        elem: '#table'
        // ,height:300
        , even: false //开启隔行背景
        , url: $ctx + '/vJkPzst/listByMonthAndCompany'
        , where: {beginMonth: beginMonth, endMonth: endMonth, companyId: companyId, empNo: ""}
        , headers: {"tenantName": "slave" + companyId}
        , page: false
        , loading: true
        , cols: [[
            {checkbox: true, rowspan: 2, align: 'center', hide: true}
            , {field: '日期', title: '日期', width: 110, align: 'center', rowspan: 2}
            , {field: '凭证号', title: '凭证号', width: 90, align: 'center', rowspan: 2, hide: true}
            // , {title: '部门', align: 'center', colspan: 2, hide: true}
            // , {title: '个人', align: 'center', colspan: 2, hide: true}
            , {
                field: '职员名称', title: '职员名称', width: 130, align: 'center',
                templet: function (d) {
                    return empsMap[d.职员编码] ? empsMap[d.职员编码]["name"] : "";
                }
            }
            , {field: '摘要', title: '摘要', width: 550, rowspan: 2}
            , {field: '借方金额', title: '借方金额', width: 100, align: 'center', rowspan: 2}
            , {field: '贷方金额', title: '贷方金额', width: 100, align: 'center', rowspan: 2}
            , {
                field: '方向', title: '方向', width: 60, align: 'center', rowspan: 2,
                templet: function (d) {
                    if (d.余额金额 === 0) {
                        return '平'
                    } else if (d.余额金额 > 0) {
                        return '贷'
                    } else {
                        return '借'
                    }
                }
            }
            , {
                field: '余额', title: '余额金额', width: 150, align: 'center', rowspan: 2,
                templet: function (d) {
                    return Math.abs(d.余额金额)
                }
            }
        ],
            [
                {field: '部门编码', title: '编码', width: 120, align: 'center', hide: true}
                , {
                field: '部门名称', title: '名称', width: 130, align: 'center',
                templet: function (d) {
                    return empsMap[d.职员编码] ? empsMap[d.职员编码]["departmentname"] : "";
                }, hide: true
            }
                , {field: '职员编码', title: '编码', width: 90, align: 'center', hide: true}
            //     , {
            //     field: '职员名称', title: '名称', width: 130, align: 'center',
            //     templet: function (d) {
            //         return empsMap[d.职员编码] ? empsMap[d.职员编码]["name"] : "";
            //     }, hide: true
            // }
            ]
        ]
        , done: function (res, curr, count) {
            tableList = res.data;
            tableList.forEach(function (item, index) {
                if (item.摘要 === "合计") {
                    var tr = $(".layui-table tbody tr[data-index=" + index + "]");
                    tr.css("background-color", "yellow");
                    tr.css("font-weight", "bold");
                }
            });
            updateTableSize();
        }
    });
//重载
    var active = {
        reload: function () {
            //执行重载
            table.reload('table', {
                page: false
                , loading: true
                , where: {
                    beginMonth: beginMonth,
                    endMonth: endMonth,
                    companyId: companyId,
                    empNo: empNo
                }
                , headers: {"tenantName": "slave" + companyId}
                , done: function (res, curr, count) {
                    tableList = res.data;
                    tableList.forEach(function (item, index) {
                        if (item.摘要 === "合计") {
                            var tr = $(".layui-table tbody tr[data-index=" + index + "]");
                            tr.css("background-color", "yellow");
                            tr.css("font-weight", "bold");
                        }
                    });
                }
            }, 'data');
        }
    };

//初始化导入文件弹窗
    var layer = layui.layer;
//查询按钮
    $('#queryBtn').on('click', function () {
        beginMonth = $("#beginMonth").val();
        endMonth = $("#endMonth").val();
        companyId = $("#companies").val();
        empNo = empSelctDom.getValue("valueStr");
        selEmpNoArr = empNo === "" ? allEmpNoArr : empSelctDom.getValue("value");
        if (beginMonth > endMonth) {
            layer.alert('开始月份不能大于结束月份!');
            return;
        }
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
    //发送邮件
    $('#sendMailBtn').on('click', function () {
        if (tableList.length === 0) {
            layer.alert("无数据可发送！");
            return false;
        }
        layer.confirm('确定要给以下职员发送邮件?', {icon: 3, title: '提示'}, function (index) {
            for (var j = 0; j < selEmpNoArr.length; j++) {
                var email = empsMap[selEmpNoArr[j]]["email"];
                var empName = empsMap[selEmpNoArr[j]]["name"];
                if (email) {
                    //对电子邮件的验证
                    var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
                    if (!myreg.test(email)) {
                        layer.alert("职员 " + empName + " 的邮箱格式不正确！");
                        return false;
                    }
                    var dataHtml = "";
                    for (var i = 0; i < tableList.length; i++) {
                        var rowData = tableList[i];
                        if (rowData.职员编码 === selEmpNoArr[j]) {
                            if (rowData.余额金额 === 0) {
                                rowData["方向"] = '平'
                            } else if (rowData.余额金额 > 0) {
                                rowData["方向"] = '贷'
                            } else {
                                rowData["方向"] = '借'
                            }
                            rowData["余额"] = Math.abs(rowData.余额金额);
                            rowData["职员名称"] = empsMap[rowData.职员编码] ? empsMap[rowData.职员编码]["name"] : "";
                            rowData["部门名称"] = empsMap[rowData.职员编码] ? empsMap[rowData.职员编码]["departmentname"] : "";
                            dataHtml += "<tr>" +
                                "<td align='center'>" + rowData.日期 + "</td>" +
                                // "<td align='center'>" + rowData.凭证号 + "</td>" +
                                // "<td align='center'>" + rowData.部门编码 + "</td>" +
                                // "<td align='center'>" + rowData.部门名称 + "</td>" +
                                // "<td align='center'>" + rowData.职员编码 + "</td>" +
                                "<td align='center'>" + rowData.职员名称 + "</td>" +
                                "<td>" + rowData.摘要 + "</td>" +
                                "<td align='center'>" + rowData.借方金额 + "</td>" +
                                "<td align='center'>" + rowData.贷方金额 + "</td>" +
                                "<td align='center'>" + rowData.方向 + "</td>" +
                                "<td align='center'>" + rowData.余额 + "</td>" +
                                "</tr>"
                        }
                    }
                    if (dataHtml === '') {
                        continue;
                    }
                    var html = '<div ><h2>' + beginMonth + '月至' + endMonth + '月费用报销自动对账单-' + empName + '</h2></div>' +
                        '<table cellspacing="0" cellpadding="0" border="1">' +
                        '<thead>' +
                        '<tr>' +
                        '<th rowspan="2" align="center" width="110">日期</th>' +
                        // '<th rowspan="2" align="center" width="100">凭证号</th>' +
                        // '<th colspan="2" data-unresize="true" align="center">部门</th>' +
                        // '<th colspan="1" data-unresize="true" align="center">个人</th>' +
                        '<th align="center" width="120">职员名称</th>' +
                        '<th rowspan="2" align="center" width="350">摘要</th>' +
                        '<th rowspan="2" align="center" width="100">借方金额</th>' +
                        '<th rowspan="2" align="center" width="100">贷方金额</th>' +
                        '<th rowspan="2" align="center" width="60">方向</th>' +
                        '<th rowspan="2" align="center" width="100">余额金额</th>' +
                        '</tr>' +
                        // '<tr>' +
                        // '<th align="center" width="110">编码</th>' +
                        // '<th align="center" width="120">名称</th>' +
                        // '<th align="center" width="80">编码</th>' +
                        // '<th align="center" width="120">名称</th>' +
                        // '</tr>' +
                        '</thead><tbody>';
                    html += dataHtml + '</tbody></table>';
                    //
                    jQuery.ajax({
                        url: $ctx + '/mail/sendMail',
                        dataType: 'json',
                        data: {
                            email: email,
                            title: beginMonth + "月至" + endMonth + '月费用报销自动对账单-' + empName,
                            content: html
                        },
                        type: 'post',
                        success: function (data) {
                            layer.msg('邮件发送成功!');
                        }
                    });
                } else {
                    layer.alert("职员 " + empName + " 未设置邮箱！");
                }
            }
            layer.close(index);
        });
    });
})
;
